package builtin

import (
	"bufio"
	"context"
	"fmt"
	"os"
	"os/signal"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	"pwsh-go/internal/algorithms"
	"pwsh-go/internal/powershell"
)

// agentState represents the current state of the PowerShell agent
type agentState int32

const (
	stateIdle    agentState = iota // 等待用户提需求
	stateRunning agentState = iota // 正在执行命令（锁需求输入）
	stateDiag    agentState = iota // 出错，正在诊断/自修复
)

// PowerShell specific constants
const (
	// systemPrompt is the system prompt for the PowerShell agent
	systemPrompt = `You are PowerShell-Agent, a code-only assistant.
用户用任意语言描述需求 → 你只返回单行或多行可直接执行的 PowerShell 代码，不要任何解释、列表、Markdown、引号、代码块标记。
如果需求模糊，先返回 Write-Error '需求不明确：请补充 {缺失信息}' 这一行可执行代码，让用户二次澄清。
禁止输出非代码内容；禁止把代码包在三个反引号或 Markdown 列表里。
当用户输入 help 时，返回以下单行字符串：
Write-Host '可用指令: help/clear/exit/history ─ 用法见文档'
当用户输入 clear 时，返回：
Clear-Host
当用户输入 history 时，返回：
Get-History | Format-Table -Auto
当用户输入 exit 时，返回：
exit
需要复杂逻辑时，优先使用原生 cmdlet（如 Test-Connection、Resolve-DnsName），其次再调用 .NET 方法。
所有输出必须是 UTF-8 编码，兼容 Windows PowerShell 5.1 与 PowerShell 7+。`

	// powershellHelpText provides detailed help information for the PowerShell Agent
	powershellHelpText = `
🔍 Windows PowerShell Agent 帮助信息

功能概述:
  - 专注于 Windows 系统环境，仅支持 PowerShell 命令
  - 提供智能命令建议、错误修正和任务自动化
  - 支持上下文理解，记住之前的命令和结果

基本命令:
  - help: 显示此帮助信息
  - history: 显示命令历史
  - clear: 清除对话历史
  - exit: 退出 Agent 模式

交互方式:
  - 输入自然语言描述您的需求
  - 确认命令执行: y(执行)、n(取消)、e(编辑)
  - 命令执行后会自动分析结果并提供后续建议

PowerShell 特性支持:
  - 支持所有标准 PowerShell cmdlet (Get-*, Set-*, New-* 等)
  - 支持管道操作 (|) 和参数传递
  - 支持脚本块和多行命令
  - 自动将 Bash/Linux 命令转换为 PowerShell 等效命令
`
)

// 危险命令列表
// 需要确认的删除和修改操作命令
var confirmationRequiredCommands = []string{
	// 删除操作
	"rm", "del", "remove-item", "clear-recyclebin",
	// 修改操作
	"format", "set-executionpolicy", "remove-computer", "disable-computerrestore",
	// 系统级修改
	"shutdown", "restart-computer", "stop-process", "kill", "taskkill",
}

// PowerShell command validation regex patterns
var (
	// bashCommandPattern detects common Bash/Linux commands that should be converted to PowerShell
	bashCommandPattern = regexp.MustCompile(`(?i)^(ls|grep|cat|rm|cp|mv|touch|mkdir|chmod|chown|ps aux|kill|find|sed|awk|df|du|tar|wget|curl|sudo|apt|yum|ifconfig|man|top|uname|whoami|ssh|scp|rsync|systemctl|service|crontab|iptables|netstat|ping|traceroute|dig|nslookup|telnet|ftp|vi|nano|less|more|head|tail|wc|sort|uniq|cut|paste|tr|diff|patch|gzip|gunzip|zip|unzip|tar|ln|chgrp|dd|df|mount|umount|fdisk|mkfs|fsck|lsblk|lsof|ps|pgrep|pkill|nice|renice|bg|fg|jobs|nohup|screen|tmux|at|batch|watch|seq|xargs|expr|test|source|alias|export|echo|printf|read|set|unset|shift|trap|wait|exec|eval|ulimit|umask|getopts|declare|typeset|local|readonly|let|bc|dc|factor|seq|shuf|basename|dirname|realpath|pwd|cd|pushd|popd|dirs|mkdir|rmdir|rm|cp|mv|ln|touch|stat|file|find|locate|which|type|command|time|date|cal|sleep|usleep|history|fc|logout|exit|logout|su|sudo|chroot|env|printenv|set|export|source|unset|eval|exec|nohup|nice|renice|kill|pkill|killall|wait|disown|trap|command|builtin|enable|help|type|hash|bind|alias|unalias|dircolors|dirs|popd|pushd|shopt|suspend|times|ulimit|umask|wait|bg|fg|jobs|disown|times|suspend|logout|exit|cd|pwd|readonly|unset|shift|caller|complete|compgen|compopt|mapfile|readarray|typeset|declare|local|readonly|let|bc|dc|factor|seq|shuf|basename|dirname|realpath|pwd|cd|pushd|popd|dirs|mkdir|rmdir|rm|cp|mv|ln|touch|stat|file|find|locate|which|type|command|time|date|cal|sleep|usleep|history|fc|logout|exit|logout|su|sudo|chroot|env|printenv|set|export|source|unset|eval|exec|nohup|nice|renice|kill|pkill|killall|wait|disown|trap|command|builtin|enable|help|type|hash|bind|alias|unalias|dircolors|dirs|popd|pushd|shopt|suspend|times|ulimit|umask|wait|bg|fg|jobs|disown|times|suspend|logout|exit|cd|pwd)\b`)

	// powershellVerbPattern matches standard PowerShell verb-noun pattern
	powershellVerbPattern = regexp.MustCompile(`(?i)^(Get|Set|New|Remove|Start|Stop|Restart|Test|Update|Install|Import|Export|Add|Clear|Copy|Move|Rename|Show|Write|Read|Out|Format|Invoke|Convert|Measure|Select|Where|ForEach|Sort|Group|Join|Split|Compare|Merge|Trace|Debug|Suspend|Resume|Wait|Use|Search|Confirm|Mount|Dismount|Enable|Disable|Optimize|Backup|Restore|Sync|Grant|Revoke|Lock|Unlock|Protect|Unprotect|Limit|Reset|Repair|Expand|Compress|Resolve|Test|Approve|Assert|Complete|Compress|ConvertFrom|ConvertTo|Deny|Deploy|Disable|Disconnect|Dismount|Edit|Enable|Enter|Exit|Find|Format|Get|Grant|Group|Hide|Initialize|Install|Invoke|Join|Limit|Lock|Measure|Mount|Move|New|Open|Optimize|Out|Ping|Pop|Protect|Publish|Push|Read|Receive|Redo|Register|Remove|Rename|Repair|Request|Reset|Resize|Resolve|Restart|Restore|Resume|Revoke|Save|Search|Select|Send|Set|Show|Skip|Split|Start|Step|Stop|Submit|Suspend|Switch|Sync|Test|Trace|Unblock|Undo|Uninstall|Unlock|Unprotect|Unpublish|Unregister|Update|Use|Wait|Watch|Write)\-[A-Za-z]+`)

	// bashToPowerShellMap maps common Bash commands to their PowerShell equivalents
	bashToPowerShellMap = map[string]string{
		// 文件系统操作
		"ls":     "Get-ChildItem",
		"grep":   "Select-String",
		"cat":    "Get-Content",
		"rm":     "Remove-Item",
		"cp":     "Copy-Item",
		"mv":     "Move-Item",
		"touch":  "New-Item -ItemType File",
		"mkdir":  "New-Item -ItemType Directory",
		"rmdir":  "Remove-Item",
		"ln":     "New-Item -ItemType SymbolicLink",
		"chmod":  "Set-Acl",
		"chown":  "Set-Acl",
		"find":   "Get-ChildItem -Recurse | Where-Object",
		"locate": "Get-ChildItem -Recurse | Where-Object",
		"stat":   "Get-Item",
		"file":   "Get-Item",
		"pwd":    "Get-Location",
		"cd":     "Set-Location",
		"pushd":  "Push-Location",
		"popd":   "Pop-Location",
		"dirs":   "Get-Location -Stack",

		// 进程管理
		"ps":     "Get-Process",
		"ps aux": "Get-Process",
		"kill":   "Stop-Process",
		"pkill":  "Stop-Process -Name",
		"top":    "Get-Process | Sort-Object -Property CPU -Descending",
		"jobs":   "Get-Job",
		"bg":     "Start-Job",
		"fg":     "Wait-Job",
		"nohup":  "Start-Process",

		// 系统信息
		"df":       "Get-PSDrive",
		"du":       "Get-ChildItem -Recurse | Measure-Object -Property Length -Sum",
		"ifconfig": "Get-NetIPConfiguration",
		"uname":    "$PSVersionTable",
		"whoami":   "$env:USERNAME",
		"hostname": "$env:COMPUTERNAME",
		"uptime":   "(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime",
		"lsblk":    "Get-Disk",
		"lsof":     "Get-Process | ForEach-Object { $_.Modules }",
		"lsusb":    "Get-PnpDevice -PresentOnly | Where-Object { $_.Class -eq 'USB' }",
		"lspci":    "Get-PnpDevice -PresentOnly",

		// 网络工具
		"wget":       "Invoke-WebRequest",
		"curl":       "Invoke-WebRequest",
		"netstat":    "Get-NetTCPConnection",
		"ping":       "Test-Connection",
		"traceroute": "Test-NetConnection -TraceRoute",
		"nslookup":   "Resolve-DnsName",
		"dig":        "Resolve-DnsName",
		"ssh":        "ssh",    // Windows 10 1809+ 内置 OpenSSH 客户端
		"scp":        "scp",    // Windows 10 1809+ 内置 OpenSSH 客户端
		"telnet":     "telnet", // 需要启用 Windows 功能
		"ftp":        "ftp",    // Windows 内置
		"iptables":   "New-NetFirewallRule",

		// 文本处理
		"head":  "Get-Content -TotalCount",
		"tail":  "Get-Content -Tail",
		"wc":    "Measure-Object",
		"sort":  "Sort-Object",
		"uniq":  "Get-Unique",
		"cut":   "Select-Object",
		"paste": "Join-String",
		"tr":    "$_.Replace",
		"diff":  "Compare-Object",
		"sed":   "$_ -replace",
		"awk":   "ForEach-Object { }",

		// 压缩/解压
		"zip":    "Compress-Archive",
		"unzip":  "Expand-Archive",
		"tar":    "tar", // Windows 10 1803+ 内置 tar
		"gzip":   "Compress-Archive",
		"gunzip": "Expand-Archive",

		// 其他常用命令
		"man":     "Get-Help",
		"echo":    "Write-Output",
		"printf":  "Write-Host -NoNewline",
		"date":    "Get-Date",
		"cal":     "Get-Date | ForEach-Object { [System.Globalization.DateTimeFormatInfo]::CurrentInfo.Calendar.GetDaysInMonth($_.Year, $_.Month) }",
		"sleep":   "Start-Sleep",
		"history": "Get-History",
		"alias":   "Get-Alias",
		"which":   "Get-Command",
		"time":    "Measure-Command",
		"crontab": "Get-ScheduledTask",
		"watch":   "while($true) { Clear-Host; <command>; Start-Sleep -Seconds <interval> }",
		"xargs":   "ForEach-Object",
		"sudo":    "Start-Process -Verb RunAs",
		"su":      "Start-Process -Credential (Get-Credential)",
		"env":     "Get-ChildItem Env:",
		"export":  "$env:",
		"source":  ". <script.ps1>",
	}
)

// startAgent starts the AI agent interactive mode
func startAgent() error {
	if activeClient == nil {
		return fmt.Errorf("❌ 请先连接 AI 服务 (使用 'ai openai' 或 'ai coze')")
	}

	backend, err := powershell.NewBackend()
	if err != nil {
		return fmt.Errorf("failed to create PowerShell backend: %w", err)
	}

	// 获取当前工作目录
	wd, err := os.Getwd()
	if err != nil {
		wd = "未知目录"
	}

	// 初始化上下文消息
	contextMessages := []Message{
		{
			Role:    "system",
			Content: systemPrompt,
		},
	}

	// 初始化性能优化组件
	aiOptimizer := algorithms.NewAIOptimizer()
	workerPool := algorithms.NewWorkerPool(4, 100) // 4个工作协程，缓冲区100
	batchProcessor := algorithms.NewBatchProcessor(10, func(batch []interface{}) ([]interface{}, error) {
		// 批处理逻辑可以根据需要实现
		return batch, nil
	})
	inferenceAccel := algorithms.NewInferenceAccelerator()
	responseOptimizer := algorithms.NewResponseOptimizer()
	toolSystem := algorithms.NewToolSystem()

	agent := &aiAgent{
		backend:           backend,
		reader:            bufio.NewReader(os.Stdin),
		workingDirectory:  wd,
		messages:          make([]Message, 0),
		contextMessages:   contextMessages,
		commandHistory:    make([]string, 0),
		aiOptimizer:       aiOptimizer,
		workerPool:        workerPool,
		batchProcessor:    batchProcessor,
		inferenceAccel:    inferenceAccel,
		responseOptimizer: responseOptimizer,
		toolSystem:        toolSystem,
	}

	// 启动工作池
	agent.workerPool.Start()
	defer agent.workerPool.Stop()

	// 设置初始状态
	atomic.StoreInt32((*int32)(&agent.state), int32(stateIdle))

	fmt.Println("🤖 Windows PowerShell Agent 模式已启动！")
	fmt.Println("💡 描述您的需求，我会推荐适合的 PowerShell 命令")
	fmt.Println("📝 输入 'exit' 退出，输入 'help' 查看更多命令")
	fmt.Println("")

	// 显示上次失败记录
	agent.showLastFailure()

	return agent.runAgentMode()
}

// ExecutionJob 实现Job接口的执行任务
type ExecutionJob struct {
	id         string
	cmd        string
	backend    powershell.Backend
	resultChan chan struct {
		result string
		err    error
	}
}

// Execute 实现Job接口
func (ej *ExecutionJob) Execute() (interface{}, error) {
	result, err := ej.backend.Execute(ej.cmd)
	ej.resultChan <- struct {
		result string
		err    error
	}{result: result, err: err}
	return result, err
}

// ID 实现Job接口
func (ej *ExecutionJob) ID() string {
	return ej.id
}

// aiAgent manages the interactive AI assistant state and operations
type aiAgent struct {
	mu                sync.Mutex
	state             int32 // 使用 atomic 操作
	backend           powershell.Backend
	reader            *bufio.Reader
	lastCommand       string
	lastCommandOutput string
	lastError         string
	commandHistory    []string
	workingDirectory  string
	messages          []Message
	contextMessages   []Message
	currentProcess    *os.Process // 当前执行的子进程
	processMu         sync.Mutex  // 保护子进程操作
	ctx               context.Context
	cancel            context.CancelFunc

	// 性能优化组件
	aiOptimizer       *algorithms.AIOptimizer
	workerPool        *algorithms.WorkerPool
	batchProcessor    *algorithms.BatchProcessor
	inferenceAccel    *algorithms.InferenceAccelerator
	responseOptimizer *algorithms.ResponseOptimizer
	toolSystem        *algorithms.ToolSystem
}

// getState 安全获取当前状态
func (a *aiAgent) getState() agentState {
	return agentState(atomic.LoadInt32(&a.state))
}

// setState 安全设置状态
func (a *aiAgent) setState(state agentState) {
	atomic.StoreInt32(&a.state, int32(state))
}

// showLastFailure 显示上次失败记录
func (a *aiAgent) showLastFailure() {
	historyFile := a.getHistoryFile()
	if content, err := os.ReadFile(historyFile); err == nil {
		lines := strings.Split(string(content), "\n")
		for i := len(lines) - 1; i >= 0; i-- {
			line := strings.TrimSpace(lines[i])
			if line == "" {
				continue
			}
			parts := strings.Split(line, "│")
			if len(parts) >= 3 {
				exitCode := strings.TrimSpace(parts[1])
				if exitCode != "0" {
					fmt.Printf("\033[33m💡 上次失败记录: %s\033[0m\n", line)
					break
				}
			}
		}
	}
}

// getHistoryFile 获取历史文件路径
func (a *aiAgent) getHistoryFile() string {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return ".pwsh_agent.history"
	}
	pwshDir := filepath.Join(homeDir, ".pwsh")
	os.MkdirAll(pwshDir, 0755)
	return filepath.Join(pwshDir, "agent.history")
}

// logCommand 记录命令到历史文件
func (a *aiAgent) logCommand(cmd string, exitCode int, duration time.Duration) {
	historyFile := a.getHistoryFile()
	timestamp := time.Now().Format("2006-01-02 15:04:05")
	logEntry := fmt.Sprintf("%s│%d│%s\n", timestamp, exitCode, cmd)

	f, err := os.OpenFile(historyFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return
	}
	defer f.Close()
	f.WriteString(logEntry)
}

// runAgentMode starts the interactive agent mode
func (a *aiAgent) runAgentMode() error {
	a.setState(stateIdle)
	a.mu.Lock()
	a.messages = []Message{}
	a.mu.Unlock()

	// 设置信号处理
	a.ctx, a.cancel = context.WithCancel(context.Background())
	defer a.cancel()

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

	go func() {
		for {
			select {
			case <-sigChan:
				a.handleCtrlC()
			case <-a.ctx.Done():
				return
			}
		}
	}()

	// 获取当前 PowerShell 版本信息
	psVersionInfo, err := a.backend.Execute("$PSVersionTable | Format-List")
	if err == nil {
		// 添加版本信息到上下文
		a.contextMessages = append(a.contextMessages, Message{
			Role:    "system",
			Content: fmt.Sprintf("Current PowerShell environment: %s", psVersionInfo),
		})
	}

	fmt.Println("🤖 Windows PowerShell Agent 模式 - 输入自然语言需求，我会推荐适合的 PowerShell 命令")
	fmt.Println("💡 可用命令:")
	fmt.Println("  - help: 显示帮助信息")
	fmt.Println("  - history: 显示命令历史")
	fmt.Println("  - clear: 清除对话历史")
	fmt.Println("  - exit: 退出 Agent 模式")
	fmt.Println("")

	for {
		select {
		case <-a.ctx.Done():
			return nil
		default:
		}

		currentState := a.getState()

		switch currentState {
		case stateIdle:
			if err := a.handleUserInput(); err != nil {
				if err.Error() == "exit" {
					return nil
				}
				return err
			}
		case stateRunning:
			// 执行中状态，等待命令完成
			time.Sleep(100 * time.Millisecond)
		case stateDiag:
			// 诊断状态，等待诊断完成
			time.Sleep(100 * time.Millisecond)
		default:
			return fmt.Errorf("invalid state: %d", currentState)
		}
	}
}

// handleCtrlC 处理 Ctrl-C 信号
func (a *aiAgent) handleCtrlC() {
	currentState := a.getState()

	switch currentState {
	case stateRunning, stateDiag:
		// 执行中或诊断中，杀死子进程
		a.processMu.Lock()
		if a.currentProcess != nil {
			a.currentProcess.Kill()
			a.currentProcess = nil
		}
		a.processMu.Unlock()

		fmt.Printf("\033[31m🛑 已中止\033[0m\n")
		a.setState(stateIdle)
		a.showPrompt()
	case stateIdle:
		// 空闲状态，退出 agent
		fmt.Printf("\033[32m👋 再见\033[0m\n")
		a.cancel()
	}
}

// showPrompt 显示输入提示
func (a *aiAgent) showPrompt() {
	fmt.Print("🔍 请描述您的需求: ")
}

// handleUserInput handles user input for natural language requirements
func (a *aiAgent) handleUserInput() error {
	currentState := a.getState()
	if currentState != stateIdle {
		fmt.Printf("\033[33m⏳ 正在执行，请稍候…\033[0m\n")
		return nil
	}

	a.showPrompt()
	line, err := a.reader.ReadString('\n')
	if err != nil {
		return fmt.Errorf("failed to read input: %w", err)
	}

	line = strings.TrimSpace(line)
	if line == "" {
		return nil
	}

	// 处理特殊命令
	switch strings.ToLower(line) {
	case "exit":
		fmt.Printf("\033[32m👋 退出 PowerShell Agent 模式\033[0m\n")
		return fmt.Errorf("exit")
	case "help":
		a.showHelp()
		return nil
	case "history":
		a.showHistory()
		return nil
	case "clear":
		a.clearHistory()
		return nil
	}

	// 检查是否是JSON格式的下载诊断请求
	if strings.HasPrefix(line, "{") && strings.HasSuffix(line, "}") &&
		strings.Contains(line, "url") && strings.Contains(line, "error_code") {
		// 尝试处理为下载诊断请求
		response, err := DiagnoseDownloadError(line)
		if err == nil {
			// 成功解析并处理为下载诊断
			fmt.Println(response)
			return nil
		} else {
			// 如果解析失败，输出错误信息
			fmt.Printf("\033[31m❌ 错误：处理下载诊断请求失败: %v\033[0m\n", err)
		}
		// 继续作为普通请求处理
	}

	// 测试命令
	if line == "test download" {
		testDownloadDiagnosis()
		return nil
	}

	// 更新工作目录
	wd, err := os.Getwd()
	if err == nil && wd != a.workingDirectory {
		a.workingDirectory = wd
		// 添加工作目录变更到上下文
		a.contextMessages = append(a.contextMessages, Message{
			Role:    "system",
			Content: fmt.Sprintf("Current working directory: %s", wd),
		})
	}

	// 构建完整的消息历史，包括上下文和对话历史
	fullMessages := append([]Message{}, a.contextMessages...)
	// 添加最近的命令历史作为上下文
	if len(a.commandHistory) > 0 {
		historyContext := "Recent command history:\n"
		for i := len(a.commandHistory) - 1; i >= 0 && i >= len(a.commandHistory)-5; i-- {
			historyContext += fmt.Sprintf("%d: %s\n", len(a.commandHistory)-i, a.commandHistory[i])
		}
		fullMessages = append(fullMessages, Message{
			Role:    "system",
			Content: historyContext,
		})
	}

	// 如果有上一个命令的错误，添加到上下文
	if a.lastError != "" {
		fullMessages = append(fullMessages, Message{
			Role:    "system",
			Content: fmt.Sprintf("Previous command error: %s", a.lastError),
		})
	}

	// 添加用户对话历史
	fullMessages = append(fullMessages, a.messages...)

	// 添加当前用户请求
	fullMessages = append(fullMessages, Message{
		Role:    "user",
		Content: line,
	})

	// 简化实现，直接调用AI客户端
	response, err := activeClient(fullMessages)
	if err != nil {
		fmt.Printf("\033[31m❌ AI 调用失败: %v\033[0m\n", err)
		return nil
	}

	// 使用响应优化器优化输出
	optimizedResponse := a.responseOptimizer.OptimizeResponse(response)

	// 清理响应，提取纯代码
	command := a.extractPureCode(optimizedResponse)

	if command == "" {
		fmt.Printf("\033[31m❌ AI 未返回有效命令，请重新描述需求\033[0m\n")
		return nil
	}

	// 检查是否是模糊需求的错误提示
	if strings.HasPrefix(command, "Write-Error") && strings.Contains(command, "需求不明确") {
		fmt.Printf("\033[33m⚠️ %s\033[0m\n", command)
		return a.executeCommand(command)
	}

	// 验证是否是 PowerShell 命令
	if bashCommandPattern.MatchString(command) {
		// 检测到 Bash 命令，尝试转换为 PowerShell
		fmt.Printf("\033[33m⚠️ 检测到类 Bash 命令，尝试转换为 PowerShell 格式...\033[0m\n")

		// 首先尝试使用映射表直接转换
		commandParts := strings.Fields(command)
		if len(commandParts) > 0 {
			if powershellCmd, exists := bashToPowerShellMap[commandParts[0]]; exists {
				// 替换命令名称，保留参数
				convertedCommand := powershellCmd
				if len(commandParts) > 1 {
					// 特殊处理某些命令的参数
					switch commandParts[0] {
					case "ls":
						// 处理 ls 的常见参数
						if strings.Contains(command, " -l") {
							convertedCommand += " | Format-Table -Property Mode,Length,LastWriteTime,Name"
						} else if strings.Contains(command, " -a") {
							convertedCommand += " -Force"
						}
					case "grep":
						// 处理 grep 的参数
						if len(commandParts) >= 3 {
							pattern := commandParts[1]
							file := commandParts[2]
							convertedCommand = fmt.Sprintf("Select-String -Pattern %s -Path %s", pattern, file)
						}
					case "cat":
						// 保留文件路径参数
						if len(commandParts) >= 2 {
							convertedCommand = fmt.Sprintf("Get-Content %s", strings.Join(commandParts[1:], " "))
						}
					default:
						// 对于其他命令，简单地附加剩余参数
						convertedCommand += " " + strings.Join(commandParts[1:], " ")
					}
				}

				command = convertedCommand
				fmt.Printf("\033[36m🔄 已转换为 PowerShell 命令: %s\033[0m\n", command)
			}
		}
	}

	// 存储命令
	a.mu.Lock()
	a.lastCommand = command
	a.mu.Unlock()

	// 添加 AI 响应到历史
	a.messages = append(a.messages, Message{
		Role:    "user",
		Content: line,
	})

	a.messages = append(a.messages, Message{
		Role:    "assistant",
		Content: command,
	})

	// 检查是否需要用户确认
	if a.requiresConfirmation(command) {
		return a.handleConfirmationRequired(command)
	}

	// 自动执行其他命令
	fmt.Printf("\033[36m💡 自动执行: %s\033[0m\n", command)
	return a.executeCommand(command)
}

// requiresConfirmation 检查是否需要用户确认（仅删除和修改操作）
func (a *aiAgent) requiresConfirmation(cmd string) bool {
	cmdLower := strings.ToLower(cmd)
	for _, confirmCmd := range confirmationRequiredCommands {
		if strings.Contains(cmdLower, confirmCmd) {
			return true
		}
	}
	return false
}

// handleConfirmationRequired 处理需要确认的删除和修改操作
func (a *aiAgent) handleConfirmationRequired(cmd string) error {
	fmt.Printf("\033[33m⚠️ 删除/修改操作: %s\033[0m\n", cmd)
	fmt.Printf("\033[33m⚠️ 此操作可能影响系统或数据，输入 y 确认执行: \033[0m")

	line, err := a.reader.ReadString('\n')
	if err != nil {
		return fmt.Errorf("failed to read input: %w", err)
	}

	line = strings.TrimSpace(strings.ToLower(line))

	if line == "y" {
		fmt.Printf("\033[32m✅ 用户确认，开始执行\033[0m\n")
		return a.executeCommand(cmd)
	} else {
		fmt.Printf("\033[33m❌ 已取消执行操作\033[0m\n")
		return nil
	}
}

// handleConfirmation handles user confirmation for command execution
func (a *aiAgent) handleConfirmation(cmd string) error {
	fmt.Printf("\033[36m💡 建议执行: %s\033[0m\n", cmd)
	fmt.Print("执行吗？ [y/n/e(编辑)]: ")

	line, err := a.reader.ReadString('\n')
	if err != nil {
		return fmt.Errorf("failed to read input: %w", err)
	}

	line = strings.TrimSpace(strings.ToLower(line))

	switch line {
	case "y", "yes":
		return a.executeCommand(cmd)
	case "n", "no":
		fmt.Printf("\033[33m❌ 已取消执行，请重新描述需求\033[0m\n")
		return nil
	case "e", "edit":
		return a.editCommand(cmd)
	case "exit":
		fmt.Printf("\033[32m👋 退出 PowerShell Agent 模式\033[0m\n")
		return fmt.Errorf("exit")
	default:
		fmt.Printf("\033[33m❓ 请输入 y(执行)、n(取消)或 e(编辑)\033[0m\n")
		return a.handleConfirmation(cmd)
	}
}

// editCommand allows the user to edit the suggested command
func (a *aiAgent) editCommand(cmd string) error {
	fmt.Printf("✏️ 编辑命令 (当前: %s): ", cmd)
	line, err := a.reader.ReadString('\n')
	if err != nil {
		return fmt.Errorf("failed to read input: %w", err)
	}

	line = strings.TrimSpace(line)
	if line == "" {
		// 用户没有输入，保持原命令
		return a.handleConfirmation(cmd)
	}

	// 更新命令
	a.mu.Lock()
	a.lastCommand = line
	a.mu.Unlock()

	fmt.Printf("\033[32m✅ 命令已更新: %s\033[0m\n", line)
	return a.handleConfirmation(line)
}

// executeCommand executes the recommended command with enhanced result validation
func (a *aiAgent) executeCommand(cmd string) error {
	a.setState(stateRunning)
	defer a.setState(stateIdle)

	fmt.Printf("\033[36m⚡ 开始执行: %s\033[0m\n", cmd)
	fmt.Printf("\033[90m📝 执行时间: %s\033[0m\n", time.Now().Format("2006-01-02 15:04:05"))
	fmt.Println(strings.Repeat("-", 50))

	// 记录命令到历史
	a.mu.Lock()
	a.commandHistory = append(a.commandHistory, cmd)
	a.mu.Unlock()

	// 使用工作池异步执行命令以提升性能
	start := time.Now()
	exitCode := 0

	// 创建执行任务
	executionResult := make(chan struct {
		result string
		err    error
	}, 1)

	// 创建Job包装器
	job := &ExecutionJob{
		id:         fmt.Sprintf("exec-%d", time.Now().UnixNano()),
		cmd:        cmd,
		backend:    a.backend,
		resultChan: executionResult,
	}

	// 提交到工作池
	a.workerPool.Submit(job)

	// 等待执行完成
	execResult := <-executionResult
	result := execResult.result
	err := execResult.err
	executionTime := time.Since(start)

	// 存储执行结果
	a.mu.Lock()
	a.lastCommandOutput = result
	a.lastError = ""
	if err != nil {
		a.lastError = err.Error()
		exitCode = 1
	}
	a.mu.Unlock()

	// 记录到历史文件
	a.logCommand(cmd, exitCode, executionTime)

	// 1. 显示原始命令执行结果
	fmt.Printf("\033[90m📄 原始执行结果:\033[0m\n")
	if err != nil {
		fmt.Printf("\033[31m❌ 执行失败\033[0m\n")
		fmt.Printf("\033[90m⏱️ 耗时: %v\033[0m\n", executionTime.Round(time.Millisecond))
		fmt.Printf("\033[31m🔍 错误信息: %v\033[0m\n", err)
	} else {
		fmt.Printf("\033[32m✅ 执行成功\033[0m\n")
		fmt.Printf("\033[90m⏱️ 耗时: %v\033[0m\n", executionTime.Round(time.Millisecond))
		if len(result) > 0 {
			fmt.Println(result)
		} else {
			fmt.Printf("\033[90m(无输出内容)\033[0m\n")
		}
	}

	// 2. 验证命令执行结果的有效性
	problemType := a.validateCommandResult(cmd, result, err, exitCode)

	// 3. 如果检测到问题，进行故障排查流程
	if problemType != "" {
		a.setState(stateDiag)
		a.handleCommandProblem(cmd, result, problemType)
		a.setState(stateIdle)
	} else {
		// 命令执行正常，提供后续建议（如果适用）
		a.suggestNextActionIfApplicable(cmd, result)
	}

	fmt.Println(strings.Repeat("-", 50))
	fmt.Println("")

	return nil
}

// showHelp displays help information for the PowerShell Agent
func (a *aiAgent) showHelp() {
	fmt.Println(powershellHelpText)
}

// showHistory displays command history
func (a *aiAgent) showHistory() {
	fmt.Println("\n📜 命令历史:")
	if len(a.commandHistory) == 0 {
		fmt.Println("  (暂无命令历史)")
	} else {
		for i, cmd := range a.commandHistory {
			fmt.Printf("  %d: %s\n", i+1, cmd)
		}
	}
	fmt.Println("")
}

// clearHistory clears conversation history
func (a *aiAgent) clearHistory() {
	a.mu.Lock()
	a.messages = []Message{}
	a.commandHistory = []string{}
	a.lastError = ""
	a.lastCommandOutput = ""
	a.mu.Unlock()
	fmt.Printf("\033[32m\n🧹 已清除对话历史\n\033[0m\n")
}

// validateCommandResult validates command execution results and identifies problems
func (a *aiAgent) validateCommandResult(cmd string, result string, err error, exitCode int) string {
	// 检查是否有执行错误
	if err != nil {
		return "execution_error"
	}

	// 检查退出代码
	if exitCode != 0 {
		return "non_zero_exit"
	}

	// 检查是否为网络连接相关命令且输出为空或异常
	cmdLower := strings.ToLower(cmd)
	if a.isNetworkCommand(cmdLower) {
		if strings.TrimSpace(result) == "" {
			return "empty_network_output"
		}
		// 检查网络命令的异常输出
		if a.hasNetworkIssues(result) {
			return "network_connectivity_issue"
		}
	}

	// 检查其他类型命令的空输出问题
	if a.shouldHaveOutput(cmdLower) && strings.TrimSpace(result) == "" {
		return "unexpected_empty_output"
	}

	// 检查是否包含常见的错误指示符
	if a.hasErrorIndicators(result) {
		return "error_in_output"
	}

	return "" // 无问题
}

// isNetworkCommand checks if the command is network-related
func (a *aiAgent) isNetworkCommand(cmdLower string) bool {
	networkCommands := []string{
		"test-netconnection", "ping", "tracert", "nslookup", "netstat",
		"get-netadapter", "get-netipaddress", "get-netroute",
		"invoke-webrequest", "curl", "wget", "telnet",
	}

	for _, netCmd := range networkCommands {
		if strings.Contains(cmdLower, netCmd) {
			return true
		}
	}
	return false
}

// hasNetworkIssues checks for network connectivity issues in output
func (a *aiAgent) hasNetworkIssues(result string) bool {
	resultLower := strings.ToLower(result)
	issueIndicators := []string{
		"failed", "timeout", "unreachable", "connection refused",
		"network error", "dns resolution failed", "no route to host",
		"connection timed out", "host not found",
	}

	for _, indicator := range issueIndicators {
		if strings.Contains(resultLower, indicator) {
			return true
		}
	}
	return false
}

// shouldHaveOutput checks if a command should normally produce output
func (a *aiAgent) shouldHaveOutput(cmdLower string) bool {
	outputCommands := []string{
		"get-", "show-", "list-", "find-", "search-",
		"dir", "ls", "cat", "type", "more", "select-",
		"where-", "measure-", "format-", "out-",
	}

	for _, outCmd := range outputCommands {
		if strings.Contains(cmdLower, outCmd) {
			return true
		}
	}
	return false
}

// hasErrorIndicators checks for error indicators in command output
func (a *aiAgent) hasErrorIndicators(result string) bool {
	resultLower := strings.ToLower(result)
	errorIndicators := []string{
		"error:", "exception:", "failed:", "warning:",
		"access denied", "permission denied", "not found",
		"invalid", "cannot", "unable to",
	}

	for _, indicator := range errorIndicators {
		if strings.Contains(resultLower, indicator) {
			return true
		}
	}
	return false
}

// handleCommandProblem handles detected command problems with troubleshooting advice
func (a *aiAgent) handleCommandProblem(cmd string, result string, problemType string) {
	fmt.Printf("\033[33m\n⚠️ 检测到问题：%s\n\033[0m", a.getProblemDescription(problemType))

	// 显示故障排查建议
	troubleshootingAdvice := a.getTroubleshootingAdvice(cmd, problemType)
	fmt.Printf("\033[36m\n🔧 故障排查建议：\n%s\n\033[0m", troubleshootingAdvice)

	// 请求用户确认是否需要进一步诊断
	fmt.Printf("\033[32m\n❓ 是否需要进一步诊断？(输入 y 继续诊断，其他键跳过): \033[0m")

	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	input = strings.TrimSpace(strings.ToLower(input))

	if input == "y" || input == "yes" {
		fmt.Printf("\033[32m\n🔍 开始进一步诊断...\n\033[0m")
		a.performAdvancedDiagnosis(cmd, problemType)
	} else {
		fmt.Printf("\033[32m\n✅ 已跳过进一步诊断\n\033[0m")
	}
}

// getProblemDescription returns a description of the detected problem
func (a *aiAgent) getProblemDescription(problemType string) string {
	switch problemType {
	case "execution_error":
		return "命令执行失败"
	case "non_zero_exit":
		return "命令返回非零退出代码"
	case "empty_network_output":
		return "网络命令返回空输出"
	case "network_connectivity_issue":
		return "检测到网络连接问题"
	case "unexpected_empty_output":
		return "命令输出为空（预期应有输出）"
	case "error_in_output":
		return "输出中包含错误信息"
	default:
		return "未知问题"
	}
}

// getTroubleshootingAdvice provides troubleshooting advice based on problem type
func (a *aiAgent) getTroubleshootingAdvice(cmd string, problemType string) string {
	switch problemType {
	case "execution_error":
		return "1. 检查命令语法是否正确\n2. 确认命令是否存在于系统PATH中\n3. 检查是否有足够的权限执行该命令"
	case "non_zero_exit":
		return "1. 检查命令参数是否正确\n2. 确认目标资源是否存在\n3. 查看详细错误信息以确定具体问题"
	case "empty_network_output":
		return "1. 检查网络连接是否正常\n2. 确认目标主机/服务是否可达\n3. 检查防火墙设置是否阻止连接\n4. 验证DNS解析是否正常"
	case "network_connectivity_issue":
		return "1. 使用 ping 测试基本网络连通性\n2. 检查网络适配器状态\n3. 确认网关和DNS设置\n4. 检查代理设置（如适用）"
	case "unexpected_empty_output":
		return "1. 确认查询条件是否正确\n2. 检查目标对象是否存在\n3. 验证权限是否足够访问相关资源\n4. 尝试使用更宽泛的查询条件"
	case "error_in_output":
		return "1. 仔细阅读错误信息以了解具体问题\n2. 检查相关权限和配置\n3. 确认所需的服务或组件是否正常运行\n4. 查看系统日志获取更多信息"
	default:
		return "1. 重新执行命令确认问题\n2. 检查系统状态和资源\n3. 查看相关日志文件"
	}
}

// performAdvancedDiagnosis performs advanced diagnosis based on problem type
func (a *aiAgent) performAdvancedDiagnosis(cmd string, problemType string) {
	diagnosisCommands := a.getAdvancedDiagnosisCommands(cmd, problemType)

	for i, diagCmd := range diagnosisCommands {
		fmt.Printf("\033[36m\n🔍 诊断步骤 %d: %s\n\033[0m", i+1, diagCmd)

		// 执行诊断命令
		result, err := a.backend.Execute(diagCmd)
		exitCode := 0
		if err != nil {
			fmt.Printf("\033[31m❌ 诊断命令执行失败: %v\n\033[0m", err)
			exitCode = 1
		}

		fmt.Printf("\033[37m输出:\n%s\n\033[0m", result)

		// 检查诊断结果
		if exitCode == 0 && strings.TrimSpace(result) != "" {
			fmt.Printf("\033[32m✅ 诊断步骤 %d 完成\n\033[0m", i+1)
		} else {
			fmt.Printf("\033[33m⚠️ 诊断步骤 %d 发现异常\n\033[0m", i+1)
		}

		// 询问是否继续下一步诊断
		if i < len(diagnosisCommands)-1 {
			fmt.Printf("\033[32m\n❓ 是否继续下一步诊断？(输入 y 继续，其他键停止): \033[0m")
			reader := bufio.NewReader(os.Stdin)
			input, _ := reader.ReadString('\n')
			input = strings.TrimSpace(strings.ToLower(input))

			if input != "y" && input != "yes" {
				fmt.Printf("\033[32m\n✅ 诊断已停止\n\033[0m")
				break
			}
		}
	}

	fmt.Printf("\033[32m\n🎯 诊断完成。请根据上述信息分析问题原因。\n\033[0m")
}

// getAdvancedDiagnosisCommands returns diagnosis commands based on problem type
func (a *aiAgent) getAdvancedDiagnosisCommands(cmd string, problemType string) []string {
	switch problemType {
	case "empty_network_output", "network_connectivity_issue":
		return []string{
			"Test-NetConnection -ComputerName 8.8.8.8 -Port 53",
			"Get-NetAdapter | Where-Object Status -eq 'Up'",
			"Get-NetIPAddress -AddressFamily IPv4",
			"Get-NetRoute -DestinationPrefix 0.0.0.0/0",
			"nslookup google.com",
		}
	case "execution_error":
		return []string{
			"Get-Command " + strings.Fields(cmd)[0],
			"$env:PATH -split ';'",
			"whoami /priv",
		}
	case "unexpected_empty_output":
		return []string{
			"Get-ExecutionPolicy",
			"Get-Service | Select-Object -First 5",
			"Get-Process | Select-Object -First 5",
		}
	default:
		return []string{
			"Get-Date",
			"$PSVersionTable",
			"Get-ComputerInfo | Select-Object WindowsProductName, TotalPhysicalMemory",
		}
	}
}

// extractPureCode extracts pure PowerShell code from AI response, filtering out markdown and explanations
func (a *aiAgent) extractPureCode(response string) string {
	// 基本清理
	code := strings.TrimSpace(response)

	// 移除代码块标记
	code = strings.Trim(code, "`")
	code = strings.TrimPrefix(code, "```powershell\n")
	code = strings.TrimPrefix(code, "```PowerShell\n")
	code = strings.TrimPrefix(code, "```ps\n")
	code = strings.TrimPrefix(code, "```\n")
	code = strings.TrimPrefix(code, "```")
	code = strings.TrimSuffix(code, "```")

	// 按行处理，过滤非代码内容
	lines := strings.Split(code, "\n")
	var codeLines []string

	for _, line := range lines {
		line = strings.TrimSpace(line)

		// 跳过空行
		if line == "" {
			continue
		}

		// 跳过Markdown列表项（以数字、-、*、•开头）
		if regexp.MustCompile(`^\d+\.\s`).MatchString(line) ||
			strings.HasPrefix(line, "- ") ||
			strings.HasPrefix(line, "* ") ||
			strings.HasPrefix(line, "• ") {
			continue
		}

		// 跳过Markdown标题
		if strings.HasPrefix(line, "#") && !a.isPowerShellComment(line) {
			continue
		}

		// 跳过说明性文本（包含中文解释或英文解释）
		if a.isExplanationText(line) {
			continue
		}

		// 只保留PowerShell代码行
		if a.isPowerShellCode(line) {
			codeLines = append(codeLines, line)
		}
	}

	// 合并代码行
	result := strings.Join(codeLines, "\n")
	return strings.TrimSpace(result)
}

// isPowerShellComment checks if a line starting with # is a PowerShell comment
func (a *aiAgent) isPowerShellComment(line string) bool {
	// PowerShell注释通常紧跟#后面是空格，然后是英文或中文注释
	return regexp.MustCompile(`^#\s`).MatchString(line)
}

// isExplanationText checks if a line contains explanatory text rather than code
func (a *aiAgent) isExplanationText(line string) bool {
	// 检查是否包含解释性关键词
	explanationKeywords := []string{
		"命令：", "执行计划：", "风险提示：", "以下是", "可以", "用于", "方法：", "将显示", "很有用",
		"Command:", "Execution plan:", "Risk warning:", "The following", "can be used", "will display",
		"这个命令", "该命令", "此命令", "这些命令", "这将", "这会",
		"**", ":", "：", "。", "，", "查看", "连接的",
	}

	for _, keyword := range explanationKeywords {
		if strings.Contains(line, keyword) {
			return true
		}
	}

	// 检查是否是纯中文解释（不包含PowerShell cmdlet）
	if regexp.MustCompile(`^[\p{Han}\s，。！？：；（）]+$`).MatchString(line) {
		return true
	}

	return false
}

// isPowerShellCode checks if a line looks like PowerShell code
func (a *aiAgent) isPowerShellCode(line string) bool {
	// PowerShell注释
	if a.isPowerShellComment(line) {
		return true
	}

	// 常见PowerShell cmdlet模式
	powershellPatterns := []string{
		"Get-", "Set-", "New-", "Remove-", "Test-", "Start-", "Stop-", "Restart-",
		"Add-", "Clear-", "Copy-", "Move-", "Rename-", "Select-", "Where-Object",
		"ForEach-Object", "Sort-Object", "Group-Object", "Measure-Object",
		"Write-Host", "Write-Output", "Write-Error", "Write-Warning",
		"Import-", "Export-", "ConvertTo-", "ConvertFrom-",
	}

	for _, pattern := range powershellPatterns {
		if strings.Contains(line, pattern) {
			return true
		}
	}

	// PowerShell操作符和语法
	if strings.Contains(line, "|") || // 管道
		strings.Contains(line, "$_") || // 当前对象
		strings.Contains(line, "-eq") || strings.Contains(line, "-ne") || // 比较操作符
		strings.Contains(line, "-like") || strings.Contains(line, "-match") ||
		strings.Contains(line, ".State") || strings.Contains(line, ".Name") { // 属性访问
		return true
	}

	// 如果包含解释性文本，则不是代码
	if a.isExplanationText(line) {
		return false
	}

	return false
}

// suggestNextActionIfApplicable suggests next actions when no problems are detected
func (a *aiAgent) suggestNextActionIfApplicable(cmd string, result string) {
	// 检查是否为网络相关命令，提供相关建议
	cmdLower := strings.ToLower(cmd)
	if a.isNetworkCommand(cmdLower) {
		fmt.Printf("\033[32m\n💡 网络命令执行成功！可以尝试以下相关操作：\n\033[0m")
		fmt.Printf("\033[36m• Test-NetConnection <目标主机> -Port <端口> - 测试特定端口连接\n")
		fmt.Printf("• Get-NetAdapter - 查看网络适配器状态\n")
		fmt.Printf("• Get-NetIPAddress - 查看IP地址配置\n")
		fmt.Printf("• nslookup <域名> - 测试DNS解析\n\033[0m")
		return
	}

	// 检查是否为系统信息查询命令
	if a.isSystemInfoCommand(cmdLower) {
		fmt.Printf("\033[32m\n💡 系统信息查询成功！可以尝试以下相关操作：\n\033[0m")
		fmt.Printf("\033[36m• Get-ComputerInfo - 查看详细系统信息\n")
		fmt.Printf("• Get-Process - 查看运行进程\n")
		fmt.Printf("• Get-Service - 查看系统服务\n")
		fmt.Printf("• Get-EventLog System -Newest 10 - 查看系统日志\n\033[0m")
		return
	}

	// 检查是否为文件操作命令
	if a.isFileOperationCommand(cmdLower) {
		fmt.Printf("\033[32m\n💡 文件操作成功！可以尝试以下相关操作：\n\033[0m")
		fmt.Printf("\033[36m• Get-ChildItem -Recurse - 递归查看子目录\n")
		fmt.Printf("• Get-Item <路径> | Select-Object * - 查看详细属性\n")
		fmt.Printf("• Test-Path <路径> - 测试路径是否存在\n")
		fmt.Printf("• Get-Acl <路径> - 查看文件权限\n\033[0m")
		return
	}

	// 通用建议
	if strings.TrimSpace(result) != "" {
		fmt.Printf("\033[32m\n✅ 命令执行成功！\n\033[0m")
	}
}

// isSystemInfoCommand checks if the command is system information related
func (a *aiAgent) isSystemInfoCommand(cmdLower string) bool {
	systemCommands := []string{
		"get-computerinfo", "get-process", "get-service", "get-eventlog",
		"get-wmiobject", "get-ciminstance", "systeminfo", "tasklist",
		"get-hotfix", "get-windowsfeature",
	}

	for _, sysCmd := range systemCommands {
		if strings.Contains(cmdLower, sysCmd) {
			return true
		}
	}
	return false
}

// isFileOperationCommand checks if the command is file operation related
func (a *aiAgent) isFileOperationCommand(cmdLower string) bool {
	fileCommands := []string{
		"get-childitem", "dir", "ls", "get-item", "get-content",
		"cat", "type", "test-path", "get-acl", "set-location",
		"cd", "copy-item", "move-item", "remove-item",
	}

	for _, fileCmd := range fileCommands {
		if strings.Contains(cmdLower, fileCmd) {
			return true
		}
	}
	return false
}

// suggestErrorFix analyzes command errors and suggests fixes with intelligent diagnosis
func (a *aiAgent) suggestErrorFix(cmd string, errorMsg string) {
	// 如果错误输出为空，不提供建议
	if errorMsg == "" {
		return
	}

	// 首先检查是否有预定义的快速修复方案
	if quickFix := a.getQuickFix(cmd, errorMsg); quickFix != "" {
		fmt.Printf("\033[33m💡 快速修复建议: %s\033[0m\n", quickFix)

		// 检查修复命令是否需要用户确认
		if a.requiresConfirmation(quickFix) {
			fmt.Print("⚠️ 此修复涉及删除或修改操作，输入 y 确认执行: ")
			reader := bufio.NewReader(os.Stdin)
			response, _ := reader.ReadString('\n')
			response = strings.TrimSpace(response)

			if response == "y" || response == "Y" {
				a.executeCommand(quickFix)
			}
		} else {
			// 安全操作，自动执行
			fmt.Printf("\033[32m🚀 自动执行修复命令...\033[0m\n")
			a.executeCommand(quickFix)
		}
		return
	}

	// 智能分析错误类型并构造相应的诊断命令
	diagCmds := a.buildIntelligentDiagnosisCommands(cmd, errorMsg)

	fmt.Printf("\033[33m💡 智能诊断：正在分析错误...\033[0m\n")

	var diagResults []string
	for i, diagCmd := range diagCmds {
		fmt.Printf("\033[36m🔍 诊断步骤 %d: %s\033[0m\n", i+1, diagCmd)

		result, err := a.backend.Execute(diagCmd)
		if err != nil {
			fmt.Printf("\033[31m❌ 诊断命令执行失败: %v\033[0m\n", err)
			diagResults = append(diagResults, fmt.Sprintf("错误: %v", err))
		} else {
			fmt.Printf("\033[32m✅ 诊断完成\033[0m\n")
			diagResults = append(diagResults, result)
		}
	}

	// 使用增强的 AI 分析错误并提供修复建议
	go func() {
		// 构建更详细的错误分析上下文
		errorContext := a.buildErrorAnalysisContext(cmd, errorMsg, diagResults)

		errorAnalysisMessages := append([]Message{}, a.contextMessages...)
		errorAnalysisMessages = append(errorAnalysisMessages, Message{
			Role:    "user",
			Content: errorContext,
		})

		errorAnalysis, err := activeClient(errorAnalysisMessages)
		if err == nil && errorAnalysis != "" {
			// 清理分析结果
			errorAnalysis = strings.TrimSpace(errorAnalysis)
			errorAnalysis = strings.Trim(errorAnalysis, "`")
			errorAnalysis = strings.TrimPrefix(errorAnalysis, "```powershell\n")
			errorAnalysis = strings.TrimPrefix(errorAnalysis, "```PowerShell\n")
			errorAnalysis = strings.TrimPrefix(errorAnalysis, "```ps\n")
			errorAnalysis = strings.TrimPrefix(errorAnalysis, "```")
			errorAnalysis = strings.TrimSuffix(errorAnalysis, "```")
			errorAnalysis = strings.TrimSpace(errorAnalysis)

			if errorAnalysis != "" && errorAnalysis != cmd {
				fmt.Printf("\033[33m\n💡 AI修复建议: %s\033[0m\n", errorAnalysis)

				// 检查修复命令是否需要用户确认
				if a.requiresConfirmation(errorAnalysis) {
					fmt.Print("⚠️ 此修复涉及删除或修改操作，输入 y 确认执行: ")
					reader := bufio.NewReader(os.Stdin)
					response, _ := reader.ReadString('\n')
					response = strings.TrimSpace(response)

					if response == "y" || response == "Y" {
						a.executeCommand(errorAnalysis)
					}
				} else {
					// 安全操作，自动执行
					fmt.Printf("\033[32m🚀 自动执行修复命令...\033[0m\n")
					a.executeCommand(errorAnalysis)
				}
			} else {
				fmt.Printf("\033[33m💡 暂无有效的修复建议，请检查命令语法或参数\033[0m\n")
			}
		} else {
			fmt.Printf("\033[31m❌ AI分析失败: %v\033[0m\n", err)
		}
	}()
}

// getQuickFix returns predefined quick fixes for common errors
func (a *aiAgent) getQuickFix(cmd string, errorMsg string) string {
	errorLower := strings.ToLower(errorMsg)
	cmdLower := strings.ToLower(cmd)

	// 网络相关错误
	if strings.Contains(errorLower, "404") || strings.Contains(errorLower, "not found") {
		if strings.Contains(cmdLower, "invoke-webrequest") || strings.Contains(cmdLower, "wget") || strings.Contains(cmdLower, "curl") {
			return "# 检查URL是否正确，尝试访问网站首页\nInvoke-WebRequest -Uri 'https://www.baidu.com' -Method Head"
		}
	}

	// 权限相关错误
	if strings.Contains(errorLower, "access denied") || strings.Contains(errorLower, "unauthorized") {
		return "# 以管理员身份重新运行PowerShell\nStart-Process powershell -Verb RunAs"
	}

	// 文件不存在错误
	if strings.Contains(errorLower, "cannot find path") || strings.Contains(errorLower, "file not found") {
		return "# 检查当前目录和文件是否存在\nGet-Location; Get-ChildItem"
	}

	// 命令不存在错误
	if strings.Contains(errorLower, "not recognized") || strings.Contains(errorLower, "command not found") {
		cmdParts := strings.Fields(cmd)
		if len(cmdParts) > 0 {
			return fmt.Sprintf("# 查找相似命令\nGet-Command *%s* -ErrorAction SilentlyContinue", cmdParts[0])
		}
	}

	// 网络连接错误
	if strings.Contains(errorLower, "timeout") || strings.Contains(errorLower, "connection") {
		return "# 测试网络连接\nTest-NetConnection -ComputerName 8.8.8.8 -Port 53"
	}

	// PowerShell执行策略错误
	if strings.Contains(errorLower, "execution policy") {
		return "# 临时设置执行策略\nSet-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process"
	}

	return ""
}

// buildIntelligentDiagnosisCommands builds smart diagnosis commands based on error type
func (a *aiAgent) buildIntelligentDiagnosisCommands(cmd string, errorMsg string) []string {
	errorLower := strings.ToLower(errorMsg)
	cmdLower := strings.ToLower(cmd)
	commandParts := strings.Fields(cmd)

	var diagCmds []string

	// 根据错误类型构建诊断命令
	switch {
	case strings.Contains(errorLower, "network") || strings.Contains(errorLower, "connection") || strings.Contains(errorLower, "timeout"):
		// 网络相关错误诊断
		diagCmds = []string{
			"Test-NetConnection -ComputerName 8.8.8.8 -Port 53",
			"Get-NetAdapter | Where-Object {$_.Status -eq 'Up'}",
			"Get-DnsClientServerAddress",
		}

	case strings.Contains(errorLower, "access denied") || strings.Contains(errorLower, "unauthorized"):
		// 权限相关错误诊断
		diagCmds = []string{
			"whoami /priv",
			"[Security.Principal.WindowsIdentity]::GetCurrent().Groups | Where-Object {$_.Value -eq 'S-1-5-32-544'}",
		}

	case strings.Contains(errorLower, "file") || strings.Contains(errorLower, "path") || strings.Contains(errorLower, "directory"):
		// 文件/路径相关错误诊断
		diagCmds = []string{
			"Get-Location",
			"Get-ChildItem -ErrorAction SilentlyContinue",
		}
		// 如果命令中包含路径，检查该路径
		for _, part := range commandParts {
			if strings.Contains(part, "\\") || strings.Contains(part, "/") {
				diagCmds = append(diagCmds, fmt.Sprintf("Test-Path '%s'", part))
				break
			}
		}

	case strings.Contains(errorLower, "not recognized") || strings.Contains(errorLower, "command not found"):
		// 命令不存在错误诊断
		if len(commandParts) > 0 {
			cmdName := commandParts[0]
			diagCmds = []string{
				fmt.Sprintf("Get-Command '%s' -ErrorAction SilentlyContinue", cmdName),
				fmt.Sprintf("Get-Command *%s* -ErrorAction SilentlyContinue", cmdName),
				"$env:PATH -split ';' | ForEach-Object { Test-Path $_ }",
			}
		}

	case strings.Contains(cmdLower, "invoke-webrequest") || strings.Contains(cmdLower, "curl") || strings.Contains(cmdLower, "wget"):
		// Web请求相关错误诊断
		diagCmds = []string{
			"Test-NetConnection -ComputerName google.com -Port 80",
			"Get-NetProxy",
		}
		// 提取URL进行测试
		for _, part := range commandParts {
			if strings.HasPrefix(part, "http") {
				diagCmds = append(diagCmds, fmt.Sprintf("Test-NetConnection -ComputerName ([System.Uri]'%s').Host -Port 80", part))
				break
			}
		}

	case strings.Contains(cmdLower, "git"):
		// Git相关错误诊断
		diagCmds = []string{
			"git --version",
			"git status",
			"git config --list --local",
		}

	default:
		// 通用诊断
		if len(commandParts) > 0 {
			cmdName := commandParts[0]
			diagCmds = []string{
				fmt.Sprintf("Get-Command '%s' -ErrorAction SilentlyContinue", cmdName),
				"Get-Location",
			}
		}
	}

	// 如果没有生成任何诊断命令，提供基本诊断
	if len(diagCmds) == 0 {
		diagCmds = []string{"Get-Location", "$PSVersionTable"}
	}

	return diagCmds
}

// buildErrorAnalysisContext builds detailed context for AI error analysis
func (a *aiAgent) buildErrorAnalysisContext(cmd string, errorMsg string, diagResults []string) string {
	context := fmt.Sprintf(`作为PowerShell专家，请分析以下命令错误并提供精确的修复建议：

【原始命令】
%s

【错误信息】
%s

【系统诊断结果】
`, cmd, errorMsg)

	for i, result := range diagResults {
		context += fmt.Sprintf("诊断步骤%d结果：\n%s\n\n", i+1, result)
	}

	context += `【修复要求】
1. 只返回修复后的PowerShell命令，不要任何解释文字
2. 如果是参数错误，请修正参数
3. 如果是路径问题，请使用正确的路径格式
4. 如果是权限问题，请添加适当的权限提升
5. 如果是网络问题，请添加重试或代理设置
6. 确保命令在Windows PowerShell环境中可执行

【输出格式】
直接输出修复后的命令，不要包含任何markdown标记或解释文字。`

	return context
}

// suggestNextAction analyzes command output and suggests next steps
func (a *aiAgent) suggestNextAction(cmd string, output string) {
	// 如果输出为空或太短，不提供建议
	if len(output) < 10 {
		return
	}

	// 只对某些命令类型提供后续建议
	commandParts := strings.Fields(cmd)
	if len(commandParts) == 0 {
		return
	}

	// 获取基本命令名称
	cmdName := strings.ToLower(commandParts[0])

	// 特定命令的后续操作建议
	switch {
	// 目录列表后的建议
	case cmdName == "get-childitem" || cmdName == "dir" || strings.HasPrefix(cmd, "ls"):
		// 检查是否列出了大量文件
		lines := strings.Split(output, "\n")
		if len(lines) > 10 {
			go func() {
				// 异步提供建议，不阻塞用户交互
				time.Sleep(500 * time.Millisecond) // 稍微延迟，让用户先看到命令输出
				fmt.Printf("\033[33m\n💡 可能的后续操作:\033[0m\n")
				fmt.Println("  • 使用 Get-ChildItem -Filter *.扩展名 筛选特定文件类型")
				fmt.Println("  • 使用 Get-ChildItem | Where-Object { $_.Length -gt 1MB } 查找大文件")
				fmt.Println("  • 使用 Get-ChildItem | Sort-Object Length -Descending | Select-Object -First 5 查看最大的5个文件")
			}()
		}

	// 进程列表后的建议
	case cmdName == "get-process" || cmdName == "ps":
		go func() {
			time.Sleep(500 * time.Millisecond)
			fmt.Printf("\033[33m\n💡 可能的后续操作:\033[0m\n")
			fmt.Println("  • 使用 Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 查看 CPU 使用率最高的进程")
			fmt.Println("  • 使用 Get-Process -Name 进程名 | Select-Object * 查看特定进程的详细信息")
		}()

	// 服务列表后的建议
	case cmdName == "get-service":
		go func() {
			time.Sleep(500 * time.Millisecond)
			fmt.Printf("\033[33m\n💡 可能的后续操作:\033[0m\n")
			fmt.Println("  • 使用 Get-Service | Where-Object {$_.Status -eq 'Running'} 查看运行中的服务")
			fmt.Println("  • 使用 Get-Service -Name 服务名 | Start-Service 启动特定服务")
		}()

	// 网络配置后的建议
	case cmdName == "ipconfig" || cmdName == "get-netipaddress":
		go func() {
			time.Sleep(500 * time.Millisecond)
			fmt.Printf("\033[33m\n💡 可能的后续操作:\033[0m\n")
			fmt.Println("  • 使用 Test-NetConnection 检查网络连接")
			fmt.Println("  • 使用 Get-NetAdapter 查看网络适配器信息")
		}()

	// 对于其他命令，使用 AI 分析输出并提供建议
	default:
		// 只对输出较长的命令结果提供 AI 建议
		if len(output) > 100 && len(a.messages) > 0 && activeClient != nil {
			// 限制输出长度，避免 token 过多
			truncatedOutput := output
			if len(output) > 1000 {
				truncatedOutput = output[:1000] + "... (输出已截断)"
			}

			// 构建输出分析请求
			outputAnalysisMessages := append([]Message{}, a.contextMessages...)
			outputAnalysisMessages = append(outputAnalysisMessages, Message{
				Role:    "user",
				Content: fmt.Sprintf("分析这个 PowerShell 命令的输出，并提供一个可能的后续命令建议。只返回简短的建议，不要解释。\n\n命令: %s\n\n输出: %s", cmd, truncatedOutput),
			})

			// 异步获取 AI 建议，避免阻塞用户交互
			go func() {
				// 给异步请求一点延迟，让用户先看到输出
				time.Sleep(1 * time.Second)

				suggestion, err := activeClient(outputAnalysisMessages)
				if err == nil && suggestion != "" {
					// 清理建议
					suggestion = strings.TrimSpace(suggestion)
					suggestion = strings.Trim(suggestion, "`")
					suggestion = strings.TrimPrefix(suggestion, "```")
					suggestion = strings.TrimSuffix(suggestion, "```")
					suggestion = strings.TrimSpace(suggestion)

					// 显示建议
					fmt.Printf("\033[33m\n💡 后续建议: %s\n\033[0m\n", suggestion)
				}
			}()
		}
	}
}

// testDownloadDiagnosis 测试下载诊断功能
func testDownloadDiagnosis() {
	// 测试用例
	testCases := []struct {
		name  string
		input string
	}{
		{
			name: "QQ下载404错误",
			input: `{
				"url": "https://dldir1.qq.com/qqfile/qq/PCQQ9.7.13/QQ9.7.13.29961.exe",
				"error_code": 404,
				"error_msg": "file not exist, retcode:-46628",
				"ps_version": "5.1.22621.2506",
				"proxy_enabled": false,
				"retry_count": 0
			}`,
		},
		{
			name: "超时错误",
			input: `{
				"url": "https://example.com/large-file.exe",
				"error_code": 0,
				"error_msg": "The operation has timed out",
				"ps_version": "5.1.22621.2506",
				"proxy_enabled": false,
				"retry_count": 1
			}`,
		},
	}

	// 运行测试
	fmt.Println("===== 下载诊断功能测试 =====")
	for _, tc := range testCases {
		fmt.Printf("\n测试: %s\n", tc.name)
		fmt.Printf("输入: %s\n", tc.input)

		result, err := DiagnoseDownloadError(tc.input)
		if err != nil {
			fmt.Printf("错误: %v\n", err)
			continue
		}

		fmt.Printf("输出: %s\n", result)
	}
	fmt.Println("\n===== 测试完成 =====")
}
